package com.ly.wxstore.web.weixin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.mapper.JaxbMapper;

import com.ly.wxstore.entity.weixin.WeixinPublic;
import com.ly.wxstore.service.weixin.WeixinConf;
import com.ly.wxstore.service.weixin.WeixinMessageProcessService;
import com.ly.wxstore.service.weixin.WeixinPublicService;
import com.ly.wxstore.vo.wx.Event;
import com.ly.wxstore.vo.wx.MsgType;
import com.ly.wxstore.vo.wx.WeixinMessage;
/**
 * 微信开发者模式接入认证 Controller.
 * 
 * @author peter
 */
@Controller
@RequestMapping(value = "/wxserver")
public class WeixinPublicServerController {
	

	private static Logger logger = LoggerFactory.getLogger(WeixinPublicServerController.class);
	
	@Autowired
	private WeixinConf weixinConf;
	
	@Autowired
	private WeixinPublicService weixinPublicService;
	
	@Autowired
	private WeixinMessageProcessService weixinMessageProcessService;
	
	/**
	 * 接入认证
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		 // 微信加密签名  
        String signature = request.getParameter("signature");  
        // 时间戳  
        String timestamp = request.getParameter("timestamp");  
        // 随机数  
        String nonce = request.getParameter("nonce");  
        // 随机字符串  
        String echostr = request.getParameter("echostr");
        
        logger.info("{signature:"+signature+",timestamp:"+timestamp+",nonce:"+nonce+",echostr:"+echostr+"}");
  
        WeixinPublic weixinPublic=weixinPublicService.getById(weixinConf.getPublicId());
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (SignUtil.checkSignature(signature, timestamp, nonce, weixinPublic.getToken())) {
            return echostr;  
        }
		return "";
	}
	
	
	/**
	 * 获取微信推送过来的消息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public String receiveWeixinMessage(@RequestBody String xml,HttpServletRequest request, HttpServletResponse response, Model model) {
		// 微信加密签名  
        String signature = request.getParameter("signature");
        // 时间戳  
        String timestamp = request.getParameter("timestamp");
        // 随机数  
        String nonce = request.getParameter("nonce");
        // 随机字符串  
        String echostr = request.getParameter("echostr");
        
        logger.info("{signature:"+signature+",timestamp:"+timestamp+",nonce:"+nonce+",echostr:"+echostr+"}");
        
        logger.info("<<-------------------receiveWeixinMessage Request ---------------->>\n"+xml);
        
        WeixinMessage msg = JaxbMapper.fromXml(xml, WeixinMessage.class);
        
        String result =processWeixinMessage(msg);
        
        logger.info("<<-------------------receiveWeixinMessage Response ---------------->>\n"+result);
        return result;
	}
	
	public String processWeixinMessage(WeixinMessage msg){
		
		//文本消息
		if(MsgType.text.name().equals(msg.getMsgType())){
			return weixinMessageProcessService.processTextMsg(msg);
		}
		//事件消息
		else if(MsgType.event.name().equals(msg.getMsgType())){
			//处理事件消息
			if(Event.subscribe.name().equals(msg.getEvent())){
				
				if(StringUtils.isNotBlank(msg.getEventKey()) && msg.getEventKey().startsWith("qrscene_")){
					//扫描带参数二维码事件:用户未关注时，进行关注后的事件推送
					return weixinMessageProcessService.processScanForSubscribe(msg);
				}else{
					//普通订阅
					return weixinMessageProcessService.processSubscribeMsg(msg);
				}
				 
			}else if(Event.unsubscribe.name().equals(msg.getEvent())){
				//取消订阅
				weixinMessageProcessService.processUnsubscribe(msg);
				
			}else if(Event.SCAN.name().equals(msg.getEvent())){
				//扫描带参数二维码事件:用户已关注时的事件推送
				return weixinMessageProcessService.processScan(msg);
				
			}else if(Event.CLICK.name().equals(msg.getEvent())){
				//点击菜单事件
				return weixinMessageProcessService.processClick(msg);
			}
			
		}else{
			logger.info("未识别消息类型");
		}
		
		return "";
	}
	
	
	
}
